<!-- 分配角色 -->
<script lang="ts" setup>
import { reactive, ref } from 'vue'
import type { IDbTable } from '@/types/global'
import * as userApi from '@/api/user'
import * as roleApi from '@/api/role'
import useNotic from '@/hooks/useNotic'

defineProps({
  title: {
    type: String,
    default: ''
  }
})

// 是否显示弹窗
const showDialog = ref(false)
// 表格数据
const tableData = reactive<IDbTable>({
  pickList: [],
  total: 0,
  data: [],
  columns: [
    { label: '', type: 'tableSelect', prop: '', width: '60px', multiple: true },
    { label: '序号', type: 'index', prop: '', width: '60px' },
    { label: '角色名称', prop: 'roleName' }
  ],
  search: {
    pageNum: 1,
    pageSize: 20
  }
})
// 用户数据
const userId = ref('')

/**
 * 点击确定
 */
function submitClick() {
  const params = {
    roleIds: tableData.pickList!.map((item) => item.id),
    userId: userId.value
  }
  userApi.setUserRole(params).then((res) => {
    if (res.success) {
      useNotic().success('角色分配成功')
      showDialog.value = false
    }
  })
}
/**
 * 初始化数据并打开弹窗
 */
function init(id: string) {
  showDialog.value = true
  // 重置表格数据
  tableData.search!.pageNum = 1
  tableData.search!.pageSize = 20
  getDataList()
  // 获取用户数据
  userId.value = id
  userApi.queryUser(id).then((res) => {
    if (res.success) {
      tableData.pickList = (res.data.roleIds || []).map((item: any) => {
        return { id: item }
      })
    }
  })
}
/**
 * 获取表格数据
 */
function getDataList() {
  roleApi.getRoleByPage(tableData.search).then((res) => {
    if (res.success) {
      tableData.total = res.data.total
      tableData.data = res.data.rows.map((item: any) => {
        return { ...item, id: item.roleId }
      })
    }
  })
}

defineExpose({
  init
})
</script>

<template>
  <dui-dialog v-model="showDialog" :title="title">
    <dui-table v-bind="tableData" />
    <template #footer>
      <el-button @click="showDialog = false">关闭</el-button>
      <el-button type="primary" @click="submitClick"> 确定 </el-button>
    </template>
  </dui-dialog>
</template>
